// 购物车模块
import { getNewCartGoods, mergeLocalCart, findCartList, insertCart, deleteCart, updateCart, checkAllCart } from '@/api/cart'

export default {
  namespaced: true,
  state() {
    return {
      list: []
    }
  },

  mutations: {
    // 加入购物车
    insertCart(state, payload) {
      const sameIndex = state.list.findIndex(goods => goods.skuId === payload.skuId)
      if (sameIndex > -1) {
        const count = state.list[sameIndex].count
        payload.count += count
        state.list.splice(sameIndex, 1)
      }
      state.list.unshift(payload)
    },
    // 修改购物车
    updateCart(state, goods) {
      const updateGoods = state.list.find(item => item.skuId === goods.skuId)
      for (const key in goods) {
        if (goods[key] !== undefined && goods[key] !== null && goods[key] !== '') {
          updateGoods[key] = goods[key]
        }
      }
    },
    // 删除购物车
    deleteCart(state, skuId) {
      const index = state.list.findIndex(item => item.skuId === skuId)
      state.list.splice(index, 1)
    },
    // 设置购物车(可清空购物车)
    setCart(state, payload) {
      state.list = payload
    }
  },

  actions: {
    // 加入购物车
    insertCart(context, payload) {
      return new Promise((resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 已登录
          insertCart({ skuId: payload.skuId, count: payload.count }).then(() => {
            return findCartList()
          }).then(data => {
            context.commit('setCart', data.result)
            resolve()
          })
        } else {
          // 未登录
          context.commit('insertCart', payload)
          resolve()
        }
      })
    },
    // 获取商品列表
    findCart(context) {
      return new Promise((resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 已登录
          findCartList().then(data => {
            context.commit('setCart', data.result)
          })
        } else {
          // 未登录
          const promiseArr = context.state.list.map(goods => {
            return getNewCartGoods(goods.skuId)
          })
          Promise.all(promiseArr).then(dataList => {
            dataList.forEach((data, i) => {
              context.commit('updateCart', { skuId: context.state.list[i].skuId, ...data.result })
            })
            resolve()
          })
        }
      })
    },
    // 删除购物车
    deleteCart(context, skuId) {
      return new Promise((resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 已登录
          deleteCart([skuId]).then(data => {
            return findCartList()
          }).then(data => {
            context.commit('setCart', data.result)
          })
        } else {
          // 未登录
          context.commit('deleteCart', skuId)
          resolve()
        }
      })
    },
    // 更新购物车(选中状态、数量)
    updateCart(context, payload) {
      return new Promise((resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 已登录
          updateCart(payload).then(() => {
            return findCartList()
          }).then(data => {
            context.commit('setCart', data.result)
          })
        } else {
          // 未登录
          context.commit('updateCart', payload)
          resolve()
        }
      })
    },
    // 全选/取消全选
    checkAllCart(context, selected) {
      return new Promise((resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 已登录
          const ids = context.getters.validList.map(item => item.skuId)
          checkAllCart({ selected, ids }).then(() => {
            return findCartList()
          }).then(data => {
            context.commit('setCart', data.result)
          })
        } else {
          // 未登录
          context.getters.validList.forEach(goods => {
            context.commit('updateCart', { skuId: goods.skuId, selected })
          })
          resolve()
        }
      })
    },
    // 批量删除
    batchDeleteCart(context, isClear) {
      return new Promise((resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 已登录
          const ids = context.getters[isClear ? 'invalidList' : 'selectList'].map(item => item.skuId)
          deleteCart(ids).then(() => {
            return findCartList()
          }).then(data => {
            context.commit('setCart', data.result)
            resolve()
          })
        } else {
          // 未登录
          // isClear 为 true 删除失效列表，否则为删除选中列表
          context.getters[isClear ? 'invalidList' : 'selectList'].forEach(item => {
            context.commit('deleteCart', item.skuId)
          })
          resolve()
        }
      })
    },
    // 修改规格
    updateCartSku(context, { oldSkuId, newSku }) {
      return new Promise((resolve, reject) => {
        // 1.找出旧的商品信息
        // 2.删除旧商品数据
        // 3.原先商品数量+新skuId
        // 4.添加新的商品
        if (context.rootState.user.profile.token) {
          // 已登录
          const oldGoods = context.state.list.find(item => item.skuId === oldSkuId)
          deleteCart([oldGoods.skuId]).then(() => {
            return insertCart({ skuId: newSku.skuId, count: oldGoods.count })
          }).then(() => {
            return findCartList()
          }).then(data => {
            context.commit('setCart', data.result)
            resolve()
          })
        } else {
          // 未登录
          const oldGoods = context.state.list.find(item => item.skuId === oldSkuId)
          context.commit('deleteCart', oldSkuId)
          const { skuId, price: nowPrice, specsText: attrsText, inventory: stock } = newSku
          const newGoods = { ...oldGoods, skuId, nowPrice, attrsText, stock }
          context.commit('insertCart', newGoods)
          resolve()
        }
      })
    },
    // 合并购物车
    async mergeCart(context) {
      const cartList = context.state.list.map(goods => ({
        skuId: goods.skuId,
        selected: goods.selected,
        count: goods.count
      }))
      await mergeLocalCart(cartList)
      context.commit('setCart', [])
    }
  },

  getters: {
    // 有效商品列表
    validList(state) {
      return state.list.filter(goods => goods.stock > 0 && goods.isEffective)
    },
    // 有效商品总数
    validTotal(state, getters) {
      return getters.validList.reduce((p, c) => p + c.count, 0)
    },
    // 有效商品总价
    validAmount(state, getters) {
      return getters.validList.reduce((p, c) => p + c.count * c.nowPrice * 100, 0) / 100
    },
    // 无效商品列表
    invalidList(state) {
      return state.list.filter(goods => goods.stock <= 0 || !goods.isEffective)
    },
    // 已选商品列表
    selectList(state, getters) {
      return getters.validList.filter(item => item.selected)
    },
    // 已选商品件数
    selectedTotal(state, getters) {
      return getters.selectList.reduce((p, c) => p + c.count, 0)
    },
    // 已选商品总金额
    selectedAmount(state, getters) {
      return getters.selectList.reduce((p, c) => p + c.count * c.nowPrice * 100, 0) / 100
    },
    // 是否全选
    isCheckedAll(state, getters) {
      return (getters.validList.length !== 0 && getters.selectList.length === getters.validList.length)
    }
  }
}
